package com.fx.easyexcel.demo.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fx.easyexcel.demo.pojo.Examiner;
import com.fx.easyexcel.demo.service.ReadExcelToPdfService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Faxon
 * @version 1.0
 * @date 2020-07-03 23:10
 * 有个很重要的点 DemoDataListener 不能被spring管理，要每次读取excel都要new,然后里面用到spring可以构造方法传进去
 **/
public class ExaminerListener extends AnalysisEventListener<Examiner> {

    private static final Logger LOGGER = LoggerFactory.getLogger(ExaminerListener.class);

    /**
     * 每隔5条存储数据库，实际使用中可以3000条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 3000;
    List<Examiner> list = new ArrayList<Examiner>();

    private ReadExcelToPdfService readExcelService;

    private static ObjectMapper mapper = new ObjectMapper();
    /**
     * 如果使用了spring,请使用这个构造方法。每次创建Listener的时候需要把spring管理的类传进来
     *
     * @param readExcelService
     */
    public ExaminerListener(ReadExcelToPdfService readExcelService) {
        this.readExcelService = readExcelService;
    }

    /**
     * 这个每一条数据解析都会来调用
     *
     * @param data
     * one row value. Is is same as {@link AnalysisContext#readRowHolder()}
     * @param context
     */
    @Override
    public void invoke(Examiner data, AnalysisContext context) {
        if(data != null){
            list.add(data);
            // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
            if (list.size() >= BATCH_COUNT) {
                readExcelService.readDate(list);
                // 存储完成清理 list
                list.clear();
            }
        }
    }
    /**
     * 所有数据解析完成了 都会来调用
     *
     * @param context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        if(list.size()>0){
            readExcelService.readDate(list);
        }
    }

}